package com.example.springbootlearn.listener;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericApplicationContext;

/**
 * @author caiji Mr. Li
 * @date 2019/10/28 17:48
 */
public class ApplicationListenerOnSpringEventBootStrap {

    public static void main(String[] args) {
//        ConfigurableApplicationContext context =new GenericApplicationContext();
//        System.out.println("创建spring上下文"+context.getDisplayName());
//
//        context.addApplicationListener(event -> {
//            System.out.println("触发事件： "+event.getClass().getSimpleName());
//        });
//
//        System.out.println("应用上下文准备初始化。。。");
//        context.refresh();
//        System.out.println("应用上下文已初始化。。。");
//
//        System.out.println("应用上下文准备停止启动。。。");
//        context.stop();
//        System.out.println("应用上下文已停止启动。。。");
//
//        System.out.println("应用上下文准备启动启动。。。");
//        context.start();
//        System.out.println("应用上下文已启动启动。。。");
//
//        System.out.println("应用上下文准备关闭。。。");
//        context.close();
//        System.out.println("应用上下文已关闭。。。");


        GenericApplicationContext context = new GenericApplicationContext();
        context.registerBean(MyApplicationListener.class);
        context.refresh();

        context.publishEvent(new MyApplicationEvent("hello World!"));
        context.close();
        context.publishEvent(new MyApplicationEvent("hello World Again"));
    }

    public static class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {

        @Override
        public void onApplicationEvent(MyApplicationEvent event) {
            System.out.println(event.getClass().getSimpleName() + " : " + event.getSource().toString());
        }
    }

    public static class MyApplicationEvent extends ApplicationEvent {

        public MyApplicationEvent(Object source) {
            super(source);
        }
    }
}
